<?php
// +----------------------------------------------------------------------
// | DCloud [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.yunku.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace dc\controller;

use dragon\SysConfig;
use dragon\User\User;
use think\Db;

class AdminBaseController extends BaseController
{
    // 权限检测用: 以控制器内赋值为准
    protected $perpage = 15;
    protected $user    = null;
    protected $company = null;
    protected $companyUser = null;
    protected $unVerifiedCompanyDefaultRoute = 'main/index';

    public function _initialize()
    {
        // 监听admin_init
        hook('admin_init');
        parent::_initialize();
        $session_admin_id = session('ADMIN_ID');

        // 模拟登陆
//        if(!$session_admin_id) {
//            $user = User::get(1)->toArray();
//            $this->userLogin($user);
//            $this->redirect($_SERVER['REQUEST_URI']);
//        }
        if (!empty($session_admin_id)) {
            $user = User::get($session_admin_id);

            $user['user_nickname'] = $user['user_nickname'] ?: $user['user_login'];

            $this->setUser($user);

            $this->assign("admin", $user);
        } else {
            if ($this->request->isPost()) {
                $this->error("您还没有登录！", url("admin/public/login"));
            } else {
                header("Location:" . url("admin/public/login"));
                exit();
            }
        }
    }

    protected function userLogin($user) {
        //登入成功页面跳转
        session('ADMIN_ID', $user["id"]);
        session('name', $user["user_login"]);
        $user['last_login_ip']   = get_client_ip(0, true);
        $user['last_login_time'] = time();
        $token                     = dc_generate_user_token($user["id"], 'web');
        if (!empty($token)) {
            session('token', $token);
        }
        Db::name('user')->update($user);
        cookie("admin_username", $user["user_login"], 3600 * 24 * 30);
        session("__LOGIN_BY_DC_ADMIN_PW__", null);
    }

    protected function setUser($user) {
        $this->user = $user;
        config('user_info', $user);
        $this->assign("user_info", $user);
    }

    public function _initializeView()
    {
        $dcAdminThemePath    = config('dc_admin_theme_path');
        $dcAdminDefaultTheme = dc_get_current_admin_theme();

        $themePath = "{$dcAdminThemePath}{$dcAdminDefaultTheme}";

        $root = dc_get_root();

        //使cdn设置生效
        $cdnSettings = dc_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$root}/{$themePath}",
                '__STATIC__'   => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', "$themePath/");
        config('view_replace_str', $viewReplaceStr);
    }

    /**
     * 初始化后台菜单
     */
    public function initMenu()
    {
    }

    /**
     *  检查后台用户访问权限
     * @param int $userId 后台用户id
     * @return boolean 检查通过返回true
     */
    private function checkAccess($userId)
    {
        // 如果用户id是1，则无需判断
        if ($userId == 1) {
            return true;
        }

        $module     = $this->request->module();
        $controller = $this->request->controller();
        $action     = $this->request->action();
        $rule       = $module . $controller . $action;

        $notRequire = ["adminIndexindex", "adminMainindex"];
        if (!in_array($rule, $notRequire)) {
            return dc_auth_check($userId);
        } else {
            return true;
        }
    }

}